/*
 * To change this license header, choose License Headers in Project Properties.
 * To change this template file, choose Tools | Templates
 * and open the template in the editor.
 */
package Presentation;

import Business.EmployeeBusiness;
import Objects.Employee;
import Objects.Manager;
import java.awt.Color;
import java.awt.Dimension;
import java.awt.FlowLayout;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.HeadlessException;
import java.awt.Toolkit;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.FocusAdapter;
import java.awt.event.FocusEvent;
import java.awt.event.FocusListener;
import java.math.BigInteger;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.sql.SQLException;
import java.util.logging.Level;
import java.util.logging.Logger;
import javax.swing.DefaultComboBoxModel;
import javax.swing.ImageIcon;
import javax.swing.JButton;
import javax.swing.JComboBox;
import javax.swing.JFrame;
import javax.swing.JLabel;
import javax.swing.JOptionPane;
import javax.swing.JPanel;
import javax.swing.JPasswordField;
import javax.swing.JTextField;
import javax.swing.UIManager;
import javax.swing.UnsupportedLookAndFeelException;

/**
 *
 * @author Hoang Ngoc Nhat Anh
 */
public class FrmLogin extends JFrame implements ActionListener {

    private final ImageIcon icon = new ImageIcon(getClass().getResource("./image/bg.png"));
    public JLabel lbl;
    private JTextField txtUser;
    private JPasswordField pwPass;
    private JPanel pnl, tmp1, tmp2, tmp3, tmp4, tmp5, tmp6;
    private JComboBox cmb;
    private JButton btnLogin, btnExit;

    private String encryptPass(String text) {
        String ecryptText = null;
        try {
            MessageDigest mess = MessageDigest.getInstance("MD5");
            byte[] digest = mess.digest(text.getBytes());
            BigInteger num = new BigInteger(1, digest);

            ecryptText = num.toString(16).toUpperCase();
        } catch (NoSuchAlgorithmException ex) {
            Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }

        return ecryptText;
    }

    public FrmLogin() throws HeadlessException {
        Dimension dim = Toolkit.getDefaultToolkit().getScreenSize();
        int w = this.getSize().width;
        int h = this.getSize().height;
        int x = (dim.width - w) / 2;
        int y = (dim.height - h) / 2;

        setLayout(new FlowLayout());
      
        //txtUser.setBackground(new Color(0, 0, 0, 0));
        lbl = new JLabel("Login Wonder Lower Price");
        lbl.setText("");
        lbl.setForeground(Color.blue);
        lbl.setFont(new Font("Arial", 30, 30));
        lbl.setPreferredSize(new Dimension(400, 47));

        pnl = new JPanel() {
            @Override
            protected void paintComponent(Graphics g) {
                g.drawImage(icon.getImage(), 0, 0, null);
                super.paintComponent(g);
            }
        };
          txtUser = new JTextField("");
        txtUser.setPreferredSize(new Dimension(350, 46));
        txtUser.setFont(new Font("Tahoma", 30, 30));
 
        tmp1 = new JPanel();
        tmp1.setPreferredSize(new Dimension(50, 46));
        tmp1.setBackground(new Color(0, 0, 0, 0));
        pnl.setPreferredSize(new Dimension(512, 320));
        pnl.setOpaque(false);
        pnl.add(lbl);
        pnl.add(txtUser);
        pnl.add(tmp1);

        tmp2 = new JPanel();
        tmp2.setBackground(new Color(0, 0, 0, 0));
        tmp2.setPreferredSize(new Dimension(500, 26));
        pnl.add(tmp2);

        pwPass = new JPasswordField();
        pwPass.setPreferredSize(new Dimension(350, 46));
        pwPass.setFont(new Font("Tahoma", 30, 30));
        pnl.add(pwPass);

        tmp3 = new JPanel();
        tmp3.setPreferredSize(new Dimension(50, 46));
        tmp3.setBackground(new Color(0, 0, 0, 0));
        pnl.add(tmp3);

        tmp4 = new JPanel();
        tmp4.setBackground(new Color(0, 0, 0, 0));
        tmp4.setPreferredSize(new Dimension(500, 5));
        pnl.add(tmp4);

        DefaultComboBoxModel cmbmodel = new DefaultComboBoxModel();
        cmbmodel.addElement("Manager");
        cmbmodel.addElement("Employee");
        cmb = new JComboBox(cmbmodel);
        cmb.setPreferredSize(new Dimension(120, 30));
        cmb.setFont(new Font("Arial", Font.BOLD, 14));
        pnl.add(cmb);

        tmp5 = new JPanel();
        tmp5.setPreferredSize(new Dimension(100, 46));
        tmp5.setBackground(new Color(0, 0, 0, 0));
        pnl.add(tmp5);

        btnExit = new JButton();
        btnExit.setPreferredSize(new Dimension(80, 80));
        //btnExit.setBackground(new Color(0, 0, 0, 0));
        btnExit.setToolTipText("EXIT");
        btnExit.setContentAreaFilled(false);
        btnExit.setFocusPainted(false);
        btnExit.setBorder(null);
        pnl.add(btnExit);

        tmp6 = new JPanel();
        tmp6.setPreferredSize(new Dimension(20, 46));
        tmp6.setBackground(new Color(0, 0, 0, 0));
        pnl.add(tmp6);

        btnLogin = new JButton();
        btnLogin.setPreferredSize(new Dimension(80, 80));
       // btnLogin.setBackground(new Color(0, 0, 0, 0));
        btnLogin.setContentAreaFilled(false);
        btnLogin.setToolTipText("LOGIN");
        btnLogin.setFocusPainted(false);
        btnLogin.setBorder(null);
        pnl.add(btnLogin);

        getContentPane().add(pnl);

        setSize(512, 320);

        setUndecorated(true);
        setBackground(new Color(0, 0, 0, 0));
        setLocation(x - 256, y - 160);
        setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);

        btnLogin.addActionListener(this);
        btnExit.addActionListener(this);
        txtUser.addActionListener(this);
        pwPass.addActionListener(this);
    }

    public static void main(String[] args) {
        new FrmLogin().setVisible(true);
        try {
            UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
        } catch (ClassNotFoundException | InstantiationException | IllegalAccessException | UnsupportedLookAndFeelException ex) {
            Logger.getLogger(FrmLogin.class.getName()).log(Level.SEVERE, null, ex);
        }

    }

    private String validateForm() {
        StringBuilder err = new StringBuilder();

        if (txtUser.getText().isEmpty()) {
            err.append("\n -Type UserName Please!");
        }
        if (new String(pwPass.getPassword()).trim().isEmpty()) {
            err.append("\n -Type Password Please!");
        }
        return err.toString();
    }

    @Override
    public void actionPerformed(ActionEvent ae) {
        if (ae.getSource() == btnLogin || ae.getSource() == txtUser || ae.getSource() == pwPass) {
            String err = validateForm();
            if (err.isEmpty()) {
                if (cmb.getSelectedIndex() == 0) {

                    Manager m = new Manager();
                    String pass = new String(pwPass.getPassword()).trim();

                    m.setManagerAccount(txtUser.getText().trim());
                    m.setManagerPass(encryptPass(pass));

                    boolean check = false;
                    int kt = 0;
                    try {
                        check = Business.ManagerBusiness.isManager(m);
                    } catch (SQLException ex) {
                        kt = 1;
                        //JOptionPane.showMessageDialog(null, "Cannot connect to SQL Server", "Notification", JOptionPane.WARNING_MESSAGE);
                        int ans = JOptionPane.showConfirmDialog(null, "Cannot connect to Sql server! Do you want to config now?", "System", JOptionPane.WARNING_MESSAGE);
                        if (ans == 0) {
                            DB_Config obj = new DB_Config();
                            obj.setVisible(true);
                        } else {
                            System.exit(0);
                        }
                    } catch (ClassNotFoundException ex) {
                        ex.printStackTrace();
                    }

                    if (kt == 0) {
                        if (check == true) {
                            FrmMain frm = new FrmMain();
                            frm.receiverManager(m);
                            frm.setVisible(true);
                            this.dispose();
                        } else {
                            JOptionPane.showMessageDialog(null, "UserName or Password is not available");
                        }
                    }

                } else {
                    Employee em = new Employee();
                    String p = new String(pwPass.getPassword()).trim();
                    em.setEmployeeAccount(txtUser.getText().trim());
                    em.setEmployeePassword(encryptPass(p));
                    boolean check = false;
                    int kt = 0;
                    try {
                        check = EmployeeBusiness.isEmployee(em);
                    } catch (ClassNotFoundException ex) {
                        kt = 1;
                        JOptionPane.showMessageDialog(null, ex.getMessage(), "Notification", JOptionPane.WARNING_MESSAGE);
                    } catch (SQLException ex) {
                        JOptionPane.showMessageDialog(null, "Cannot connect to SQL Server", "Notification", JOptionPane.WARNING_MESSAGE);
                    }

                    if (kt == 0) {
                        if (check) {

                            FrmMain frm = new FrmMain();
                            frm.receiverEmployee(em);
                            frm.setVisible(true);
                            this.dispose();

                        } else {
                            JOptionPane.showMessageDialog(null, "UserName or Password is not available");
                        }
                    }
                }
            } else {
                JOptionPane.showMessageDialog(null, err,"Notification",JOptionPane.WARNING_MESSAGE);
            }



        }
        if (ae.getSource() == btnExit) {
            int ans = JOptionPane.showConfirmDialog(null, "Are you want to exit?");
            if (ans == 0) {
                System.exit(ans);
            }
        }
    }
}
